//
//  protocolA.swift
//  swiftStudy
//
//  Created by unisedu on 16/4/1.
//  Copyright © 2016年 CaoFei. All rights reserved.
//

import UIKit

class protocolA: NSObject {

}
//协议是为方法，属性等定义一套规范，没有具体的实现、
//协议能够被类，结构体等具体实现（或遵守）
//
//protocol SomeProtocol{
//    //protocol definition goes here
//}
//
//struct SomStructure:FirstProtocol , AnotherProtocol{
//    //structure definition goes here
//}
//class SomeClass:SomeSuperclass,FirstProtocol,AnotherProtocol{
//    //class definition goes here
//}

// 定义属性  oc里没有的
//协议中get set方法不用写return
//1 。 set 和 get访问器
protocol SomeProtocol {
    var mustBeSettable : Int {get set}
    var doesNotNeedToBeSettable:Int {get}
}
//2.静态属性
protocol AnotherProtocol{
    static var someTypeProperty: Int {get set}
}
//3. 只读
protocol FullyNamed{
    var fullName : String {get}
}

//例子
struct Person : FullyNamed {
    var fullName : String
}

let john = Person (fullName: "John Appleseed")
print(john.fullName)
class Starship : FullyNamed{
    var prefix: String?
    var name: String
    init (name : String , prefix: String? = nil){
        self.name = name
        self.prefix = prefix
    }
    var fullName : String {
        //应该写get{....}，由于只有一个get，那么可以省略，直接返回
        //判断prefix是否为空  prefix!表示一定不为nil
        //(prefix! + " " ) 可以不加（），为了方便理解 bool?a:b格式
        return (((prefix ? (prefix! + " " ):"") + name) != nil)
    }
    
}

var ncc1701 = Starship (name:"Enterprise" , prefix:"asdf")
print (ncc1701.fullName)




// 定义方法
protocol RandomNumberGenerator{
    func random() -> Double
}

//定义静态方法
protocol SomeProtocol2 {
    static func someTypeMethod()
}

//例子
class LinearCongruentialGenerator : RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 133364.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c ) % m )
        return lastRandom/m
    }
}


let generator = LinearCongruentialGenerator()
print ("Here's random number : \(generator.random())")
print ("And another one :\(generator.random())" )


// 把协议作为类型使用
class Dice {
    
    let sides : Int
    let generator : RandomNumberGenerator
    init(sides : Int ,generator : RandomNumberGenerator) {
        self.sides = sides
        self.generator = generator
    }
    func roll() -> Int {
        return Int ( generator.random () * Double (sides)) + 1
    }
}

var d6 = Dice (sides:6,generator : LinearCongruentialGenerator())
for _ in 1...5{
    
    print (" Random dice roll is \(d6.roll()) ")
}
